/*!\file  task.c  The tasks implementation.
 *
 *      This file is part of the micro-rtos package.
 *
 *  Copyright (c) 2008-2009 by 
		Gabriel Zabusek <gabriel.zabusek@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License
 *      as published by the Free Software Foundation; either version
 *      2 of the License, or (at your option) any later version.
 */

#include <kernel/task.h>
#include <include/std_io.h>
#include <include/types.h>

int 
task_create( task_t * pTask, void *(*task_proc)(void *) )
{
	//initialize the list node structure
	pTask->list_item.p_task = pTask;
	pTask->list_item.p_proc = task_proc;


	//stack grows downwards so set it as if it was empty
	pTask->pStackTop = pTask->StackBlock + (TASK_STACK_SIZE - 1);

	unative_t *pOrigTop = pTask->pStackTop;

	*(pTask->pStackTop) = (unative_t)task_proc + INSTR_SIZE;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)def_link;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)pOrigTop;
	pTask->pStackTop--;	
	*(pTask->pStackTop) = (unative_t)0xBEEF0012;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0011;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0010;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0009;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0008;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0007;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0006;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0005;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0004;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0003;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0002;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0001;
	pTask->pStackTop--;
	*(pTask->pStackTop) = (unative_t)0xBEEF0000;
	pTask->pStackTop--;	
	*(pTask->pStackTop) = (unative_t)0x1f; //initial spsr - system mode with irq/fiq enabled
	//pTask->pStackTop--;
	

	//add task to ready list
	list_add_tail( &((pTask->list_item).list), &(ready_list.list) );

	printk("Created task\n");
	printk("List size: %d\n", list_size(&(ready_list.list)) );
//	(pTask->list_item).p_proc( NULL );

	return 0;
}


void 
init_task(void)
{
	INIT_LIST_HEAD( &(ready_list.list) );
}
